package com.azkj.album.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.azkj.album.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class SaveImgToLocalTool {
    public static String IMAGE_NAME = "iv_share_";
    public static int  i =0;

    //根据网络图片url路径保存到本地
    public static final File saveImageToSdCard(Context context, String image, String fileNmae) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context, fileNmae);

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap =  BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, outStream);
            outStream.flush();
            outStream.close();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context, String fileName) throws IOException {
        File folder = new File(MyApplication.getApplication().getExternalFilesDir(null) + "/shareData");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File imageFile = new File(folder.getPath() + File.separator + fileName + ".png");

        if (imageFile.exists()) {
            imageFile.delete();
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imageFile;
    }
}
